package nl.hr.minor.mobilelife.j1213.jlr.findit;

import nl.hr.minor.mobilelife.j1213.jlr.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Level 4 of FindIT
 * @author Leon
 *
 */
public class SearchDifferenceFour extends Activity implements View.OnTouchListener, View.OnClickListener{
	
	public static final String LEVEL = "com.example.minigames.LEVEL_FOUR";
	public static final String SCORE = "com.example.minigames.SCORE";
	public static final String MISTAKES = "com.example.minigames.MISTAKES";
	
	private int progressScore;
	private int mistakes;

	private TextView mistakesTextView;

	private ImageView imageOne;
	private ImageView imageTwo;

	private Button buttonOne;
	private ProgressBar progressBar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.findit_search_difference_four);
		initVars();
	}

	@Override
	protected void onResume() {
		super.onResume();
		new Thread (new Runnable(){
			@Override
			public void run() {
				while(progressScore > 0){
					try {
						Thread.sleep(1000);
						progressScore -= 1;
						progressBar.setProgress(progressScore);

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	public void initVars(){

		imageOne = (ImageView) findViewById(R.id.imageOne);
		imageOne.setOnTouchListener(this);
		imageTwo = (ImageView) findViewById(R.id.imageTwo);
		imageTwo.setOnTouchListener(this);

		buttonOne = (Button) findViewById(R.id.buttonOne);
		buttonOne.setOnClickListener(this);
		progressBar = (ProgressBar) findViewById(R.id.progressBarOne);
		mistakesTextView = (TextView) findViewById(R.id.mistakes);

		progressScore = 100;
		mistakes = 0;
	}

	@Override
	public boolean onTouch(View view, MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_UP){
			mistakesTextView.setText("foutjes: "+(++mistakes));
		}
		return true;
	}
	
	@Override
	public void onClick(View v) {
		savePreferences();
		startNextLevel();
	}
	
	private void savePreferences(){
		SharedPreferences scoreSharedPreferences = 
				getSharedPreferences(LEVEL, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = scoreSharedPreferences.edit();
		editor.putInt(SCORE, progressScore);
		editor.putInt(MISTAKES, mistakes);
		editor.commit();
	}
	
	private void startNextLevel(){
		Intent intent = new Intent(this, SearchDifferenceThree.class);
		startActivity(intent);
		finish();
	}
}